import React, { useEffect, useState, memo } from 'react';
import { Spin, Button, message, Empty, Card, Dropdown, Menu, Modal } from 'antd';
import { formatMessage } from 'umi';
import cn from 'classnames';
import { connect } from 'umi';

import { withRoutePage } from '@/utils/enhanceUtils';
import { BottomAction } from '@/components';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import { isSuccess } from '@/utils/request';
import AuthComponent from '@/utils/auth/AuthComponent';

import { querySalaryMonthItemData, onEditMonthTemplate } from '@/services/salaryManage/salaryCalculate';
import { goToSalarymainadd } from '@/pages/SalaryManage/utils/pageNavigateUtil';

import { obtainDictMap } from '@/pages/SalaryManage/utils';
import tabMessageUtil, { useHandleRefreshMessage } from '@/pages/SalaryManage/utils/tabMessageUtil';
import { OrganizationNameHead } from '@/pages/SalaryManage/components/OrganizationName';
import styles from '../index.less';

const NewEmpty = memo(({ title }) => (
    <div className={styles.emptyWrap}>
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={title} />
    </div>
));

const SALARY_OBJECT_OPTIONS = 'salaryObjectOptions';
const DICT_NAME_LIST = [SALARY_OBJECT_OPTIONS];

const ItemDropDown = ({ item, children }) => {
    const [salaryObjectEnum, setSalaryObjectEnum] = useState({});

    useEffect(() => {
        obtainDictMap(DICT_NAME_LIST).then(enumMap => {
            setSalaryObjectEnum(enumMap[SALARY_OBJECT_OPTIONS]);
        });
    }, []);

    return (
        <Dropdown
            trigger={['hover']}
            getPopupContainer={triggerNode => triggerNode.parentNode}
            overlay={() => (
                <Menu className={styles.dropdownBox}>
                    <Menu.Item className={styles.dropdownItem}>
                        <span className={styles.dropdownLabel}>全称：</span>
                        <span>
                            {item.parentTitle}
                            {item.title}
                        </span>
                    </Menu.Item>
                    <Menu.Item className={styles.dropdownItem}>
                        <span className={styles.dropdownLabel}>
                            {(item.formulaFlow && '审批流：') ||
                                (item.formulaFunc && '公式：') ||
                                (item.staffInfoName && '取值关联字段：')}
                        </span>
                        <span>{item.formulaFlow || item.formulaFunc || item.staffInfoName}</span>
                    </Menu.Item>
                    <Menu.Item className={styles.dropdownItem}>
                        <span className={styles.dropdownLabel}>对象：</span>
                        <span>{salaryObjectEnum[item.salaryObject]}</span>
                    </Menu.Item>
                </Menu>
            )}
            placement="topCenter"
            mouseEnterDelay={0.3}
        >
            {children}
        </Dropdown>
    );
};

const EditSalaryMain = ({ organizationCode, location }) => {
    const [monthModalLoading, setMonthModalLoading] = useState(false);
    const [oldAddList, setOldAddList] = useState([]);
    const [oldReduceList, setOldReduceList] = useState([]);
    const [newAddList, setNewAddList] = useState([]);
    const [newReduceList, setNewReduceList] = useState([]);
    // 是否做过修改
    const [modified, setModified] = useState(false);
    const goBack = () => {
        pageTabUtil.closeTab();
    };
    const onSelectCommonMethod = (
        item,
        index,
        deleteDataList,
        deleteDataListMethod,
        addDataList,
        addDataListMethod
    ) => {
        // 删除当前已选中  移动到可添加列表中
        const deleteDataListCopy = deleteDataList.slice();
        const addDataListCopy = addDataList.slice();
        deleteDataListCopy.splice(index, 1);
        addDataListCopy.push(item);
        deleteDataListMethod(deleteDataListCopy);
        addDataListMethod(addDataListCopy);
        setModified(true);
    };
    const getPostSaveData = () => {
        const { templateId } = location.query;
        const salaryItemIds = [];
        oldAddList.forEach(item => {
            salaryItemIds.push(item.id);
        });
        oldReduceList.forEach(item => {
            salaryItemIds.push(item.id);
        });

        return { salaryItemIds, templateId };
    };
    const onModalSave = async () => {
        try {
            setMonthModalLoading(true);
            const { code, msg } = await onEditMonthTemplate(getPostSaveData());
            setMonthModalLoading(false);
            if (code === 10000) {
                message.success('保存成功！');
                tabMessageUtil.noticeFromRefresh();
                goBack();
            } else {
                message.error(msg);
            }
        } catch (e) {
            setMonthModalLoading(false);
            console.log(e);
        }
    };
    const goAdd = () => {
        if (!modified) {
            goToSalarymainadd({ query: { entry: 'mul', organizationCode } });
            return;
        }

        Modal.confirm({
            title: '确认',
            content: '有【新增】或【删除】薪资项但还未保存，保存后前往？',
            okText: '是',
            onOk: async () => {
                setMonthModalLoading(true);
                const { code, msg } = await onEditMonthTemplate(getPostSaveData());
                setMonthModalLoading(false);
                if (isSuccess(code)) {
                    goToSalarymainadd({ query: { entry: 'mul', organizationCode } });
                } else {
                    message.error(msg);
                }
            },
            cancelText: '否',
            onCancel: () => {
                goToSalarymainadd({ query: { entry: 'mul', organizationCode } });
            }
        });
    };
    const getCurrentMonthSalarySetting = async () => {
        try {
            setMonthModalLoading(true);
            const { currentYear, currentMonth } = location.query;
            const { code, data } = await querySalaryMonthItemData(organizationCode, currentYear, currentMonth);
            if (code === 10000) {
                setOldAddList(data.usedAddSalaryItems || []);
                setOldReduceList(data.usedLessSalaryItems || []);
                setNewAddList(data.unusedAddSalaryItems || []);
                setNewReduceList(data.unusedLessSalaryItems || []);
            }
            setMonthModalLoading(false);
        } catch (e) {
            console.log(e);
            setMonthModalLoading(false);
        }
    };

    const { currentMonth } = location.query;
    const cardTitle = currentMonth ? `${currentMonth}月薪资要素` : '';

    const ActionFoot = (
        <BottomAction>
            <Button onClick={goBack} disabled={monthModalLoading}>
                取消
            </Button>
            <Button type="primary" disabled={monthModalLoading} onClick={onModalSave}>
                保存
            </Button>
        </BottomAction>
    );
    useEffect(() => {
        if (organizationCode) {
            getCurrentMonthSalarySetting();
        }
    }, [organizationCode]);

    useHandleRefreshMessage();

    return (
        <PageHeaderWrapper type="success">
            <Card
                title={cardTitle}
                bordered={false}
                extra={
                    <div style={{ display: 'flex', lineHeight: '31px' }}>
                        <OrganizationNameHead organizationCode={organizationCode} />
                        {/* <AuthComponent code="finance:salary:computation:setting:itemlist">
                            <div>
                                <Button type="link" onClick={() => goToPartTemplate(organizationCode)}>
                                    <span className="iconfont iconoa_maeu_icon_regulation_default" />
                                    <span style={{ marginLeft: '5px' }}>薪资项清单</span>
                                </Button>
                            </div>
                        </AuthComponent> */}
                    </div>
                }
            >
                <div className={styles.editSalaryMainContainer}>
                    <Spin spinning={monthModalLoading}>
                        <div className={styles.editSalaryMainModalContainer}>
                            <div className={styles.oldWrap}>
                                <div className={styles.oldWrapTitle}>已添加薪资项</div>
                                <div className={styles.oldContentWrap}>
                                    <div className={styles.itemTitle}>
                                        <i
                                            className="icon iconfont iconsalary_add_icon"
                                            style={{ fontSize: 14, color: 'rgba(79, 216, 123, 1)' }}
                                        />
                                        <span className={styles.itemTitleText}>
                                            {formatMessage({ id: 'templateSetting.salaryTemplate.salaryAddItem' })}
                                        </span>
                                    </div>
                                    <div className={styles.oldItemList}>
                                        {oldAddList && oldAddList.length ? (
                                            oldAddList.map((item, index) => (
                                                <div className={styles.oldItemLabelWrap} key={item.id}>
                                                    <ItemDropDown item={item}>
                                                        <div className={styles.oldItemLabelContent}>
                                                            <span className={styles.oldItemLabel}>
                                                                {item.parentTitle}
                                                            </span>
                                                            <span className={styles.oldItemLabel}>{item.title}</span>
                                                        </div>
                                                    </ItemDropDown>
                                                    <i
                                                        className={cn('icon iconfont iconclose_o', styles.olaItemClose)}
                                                        onClick={() => {
                                                            onSelectCommonMethod(
                                                                item,
                                                                index,
                                                                oldAddList,
                                                                setOldAddList,
                                                                newAddList,
                                                                setNewAddList
                                                            );
                                                        }}
                                                    />
                                                </div>
                                            ))
                                        ) : (
                                            <NewEmpty title="薪资加项为空" />
                                        )}
                                    </div>
                                    <div className={styles.itemTitle}>
                                        <i
                                            className="icon iconfont iconsalary_minus_icon"
                                            style={{ fontSize: 14, color: 'rgba(255, 121, 67, 1)' }}
                                        />
                                        <span className={styles.itemTitleText}>
                                            {formatMessage({ id: 'templateSetting.salaryTemplate.salaryReduceItem' })}
                                        </span>
                                    </div>
                                    <div className={styles.oldItemList}>
                                        {oldReduceList && oldReduceList.length ? (
                                            oldReduceList.map((item, index) => (
                                                <div className={styles.oldItemLabelWrap} key={item.id}>
                                                    <ItemDropDown item={item}>
                                                        <div className={styles.oldItemLabelContent}>
                                                            <span className={styles.oldItemLabel}>
                                                                {item.parentTitle}
                                                            </span>
                                                            <span className={styles.oldItemLabel}>{item.title}</span>
                                                        </div>
                                                    </ItemDropDown>
                                                    <i
                                                        className={cn('icon iconfont iconclose_o', styles.olaItemClose)}
                                                        onClick={() => {
                                                            onSelectCommonMethod(
                                                                item,
                                                                index,
                                                                oldReduceList,
                                                                setOldReduceList,
                                                                newReduceList,
                                                                setNewReduceList
                                                            );
                                                        }}
                                                    />
                                                </div>
                                            ))
                                        ) : (
                                            <NewEmpty title="薪资减项为空" />
                                        )}
                                    </div>
                                </div>
                            </div>
                            <div className={styles.newWrap}>
                                <div className={styles.newWrapTitleWrap}>
                                    <div className={styles.newWrapTitle}>请点击按钮的“+”，添加需要的薪资项</div>
                                    <div className={styles.newSettingBtnWrap}>
                                        <span className={styles.newSettingBtnHit}>没有所需薪资项?</span>
                                        <AuthComponent code="finance:salary:computation:setting:salarytemp:additem">
                                            <Button
                                                type="link"
                                                onClick={goAdd}
                                                style={{ fontSize: '12px', paddingLeft: '5px', paddingRight: 0 }}
                                            >
                                                点击新增
                                            </Button>
                                        </AuthComponent>
                                    </div>
                                </div>
                                <div className={styles.newContentWrap}>
                                    <div className={styles.itemTitle}>
                                        <i
                                            className="icon iconfont iconsalary_add_icon"
                                            style={{ fontSize: 14, color: 'rgba(79, 216, 123, 1)' }}
                                        />
                                        <span className={styles.itemTitleText}>
                                            {formatMessage({ id: 'templateSetting.salaryTemplate.salaryAddItem' })}
                                        </span>
                                    </div>
                                    <div className={styles.newItemList}>
                                        {newAddList && newAddList.length ? (
                                            newAddList.map((item, index) => (
                                                <div className={styles.newItemLabelWrap} key={item.id}>
                                                    <ItemDropDown item={item}>
                                                        <div className={styles.newItemLabelContent}>
                                                            <span className={styles.newItemLabel}>
                                                                {item.parentTitle}
                                                            </span>
                                                            <span className={styles.newItemLabel}>{item.title}</span>
                                                        </div>
                                                    </ItemDropDown>
                                                    <i
                                                        className={cn(
                                                            'icon iconfont iconadd_function_o',
                                                            styles.newItemAdd
                                                        )}
                                                        onClick={() => {
                                                            onSelectCommonMethod(
                                                                item,
                                                                index,
                                                                newAddList,
                                                                setNewAddList,
                                                                oldAddList,
                                                                setOldAddList
                                                            );
                                                        }}
                                                    />
                                                </div>
                                            ))
                                        ) : (
                                            <NewEmpty title="薪资加项为空" />
                                        )}
                                    </div>
                                    <div className={styles.itemTitle}>
                                        <i
                                            className="icon iconfont iconsalary_minus_icon"
                                            style={{ fontSize: 14, color: 'rgba(255, 121, 67, 1)' }}
                                        />
                                        <span className={styles.itemTitleText}>
                                            {formatMessage({ id: 'templateSetting.salaryTemplate.salaryReduceItem' })}
                                        </span>
                                    </div>
                                    <div className={styles.newItemList}>
                                        {newReduceList && newReduceList.length ? (
                                            newReduceList.map((item, index) => (
                                                <div className={styles.newItemLabelWrap} key={item.id}>
                                                    <ItemDropDown item={item}>
                                                        <div className={styles.newItemLabelContent}>
                                                            <span className={styles.newItemLabel}>
                                                                {item.parentTitle}
                                                            </span>
                                                            <span className={styles.newItemLabel}>{item.title}</span>
                                                        </div>
                                                    </ItemDropDown>
                                                    <i
                                                        className={cn(
                                                            'icon iconfont iconadd_function_o',
                                                            styles.newItemAdd
                                                        )}
                                                        onClick={() => {
                                                            onSelectCommonMethod(
                                                                item,
                                                                index,
                                                                newReduceList,
                                                                setNewReduceList,
                                                                oldReduceList,
                                                                setOldReduceList
                                                            );
                                                        }}
                                                    />
                                                </div>
                                            ))
                                        ) : (
                                            <NewEmpty title="薪资减项为空" />
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </Spin>
                </div>
            </Card>
            {ActionFoot}
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect((state, { location }) => ({
        organizationCode: location?.query?.organizationCode
    }))(EditSalaryMain)
);
